package com.szmmsoft.mp.common.model;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szmmsoft.mp.common.constant.StringPool;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.domain.Sort;

import javax.validation.constraints.Min;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页数据请求
 *
 * @author ethan
 * @version 1.0.0
 * @since 2024-10-12
 */
@Data
@ApiModel("排序查询条件")
public class PageQuery implements Serializable {
    @ApiModelProperty(name = "页码", example = "1")
    @Min(1)
    private Integer page = 1;
    @ApiModelProperty(name = "每页条数", example = "10")
    @Min(1)
    private Integer size = 10;
    private String[] sort;

    /**
     * 解析排序条件为 Spring 分页排序实体
     *
     * @return Spring 分页排序实体
     */
    public List<OrderItem> getOrders() {
        if (ArrayUtil.isEmpty(this.sort)) {
            return new ArrayList<>();
        } else {
            List<OrderItem> orders = new ArrayList(this.sort.length);
            for (int i = 0; i < sort.length; i++) {
                List<String> sortList = CharSequenceUtil.splitTrim(sort[i], StringPool.COMMA);
                OrderItem order = new OrderItem();
                order.setAsc(Sort.Direction.valueOf((sortList.get(1)).toUpperCase()).isAscending());
                order.setColumn(CharSequenceUtil.toUnderlineCase(sortList.get(0)));
                orders.add(order);
            }
            return orders;
        }
    }

    /**
     * 基于分页查询条件转换为 MyBatis Plus 分页条件
     * Returns:
     * MyBatis Plus 分页条件
     * @return
     * @param <T>
     */
    public <T> IPage<T> toPage() {
        Page<T> myBatisPage = new Page<>((long) this.page, (long) this.size);
        List<OrderItem>orderItems = getOrders();
        if (!CollUtil.isEmpty(orderItems)){
            myBatisPage.addOrder(orderItems);
        }
        return myBatisPage;
    }
}
